package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoThreadLocal;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mappers.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author 七安
 * @since 2022-09-30
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    @Autowired
    private CourseRecordMapper courseRecordMapper;

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private MediaClient mediaClient;

    @Override
    public ResponseResult<CourseRecordVo> findMyCourseRec(Long coursePubId) throws BusinessException {
        //对传来的条件判空
        if (coursePubId == null) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //构建wrapper
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        //根据当前登陆学生的账号查询
        wrapper.eq(CourseRecord::getUserId, AuthInfoThreadLocal.getUserId());
        wrapper.eq(CourseRecord::getCoursePubId, coursePubId);
        //查询
        CourseRecord courseRecord = courseRecordMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(courseRecord)) {
            return ResponseResult.okResult();
        }
        //转成Vo对象
        CourseRecordVo courseRecordVo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
        return ResponseResult.okResult(courseRecordVo);
    }


    /**
     * 保存或更新学生的选课记录
     *
     * @param coursePubId 课程发布id
     * @param userId      用户id
     * @return 结果
     */
    @Override
    public ResponseResult saveOrUpdateCourseRec(Long coursePubId, Long userId) throws BusinessException {
        //todo 等订单写完在回来完成这个功能
        //根据课程发布id查询发布表
        ResponseResult<CoursePubVo> responseResult = contentClient.findById(coursePubId);
        //判断
        if (ErrorCode.SUCCESS.getCode() != responseResult.getCode()) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        CoursePubVo coursePubVo = responseResult.getData();
        //根据学生id和课程发布id查询选课记录
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseRecord::getUserId, userId);
        wrapper.eq(CourseRecord::getCoursePubId, coursePubId);
        CourseRecord courseRecord = courseRecordMapper.selectOne(wrapper);
        //如果存在就修改
        if (ObjectUtils.isNotEmpty(courseRecord)) {
            courseRecord.setPaid(OrdersConstants.PAID);
            courseRecordMapper.updateById(courseRecord);
        } else {
            //否则就是新增
            courseRecord = new CourseRecord();
            //设置学生id
            courseRecord.setUserId(userId);
            //设置课程发布id
            courseRecord.setCoursePubId(coursePubId);
            //设置课程发布名字
            courseRecord.setCoursePubName(coursePubVo.getName());
            //设置课程id
            courseRecord.setCourseId(coursePubVo.getCourseId());
            //设置机构id
            courseRecord.setCompanyId(coursePubVo.getCompanyId());
            //设置教育模式
            courseRecord.setTeachmode(coursePubVo.getTeachmode());
            //设置是否支付
            courseRecord.setPaid(OrdersConstants.PAID);
            //新增
            courseRecordMapper.insert(courseRecord);
        }
        return ResponseResult.okResult();
    }

    /**
     * 获取播放url
     *
     * @param coursePubId 课程发布id
     * @param mediaId     媒资id
     * @param teachplanId 教学计划id
     * @return url
     */
    @Override
    public ResponseResult<ResourceVo> getResourceUrl(Long coursePubId, Long mediaId, Long teachplanId) throws BusinessException {
        //查询课程计划
        ResponseResult<CoursePubVo> coursePubResult = contentClient.findById(coursePubId);
        //判断响应结果
        if (ErrorCode.SUCCESS.getCode() != coursePubResult.getCode()) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        CoursePubVo coursePubVo = coursePubResult.getData();
        //判断是收费课程还是免费课程
        if (CourseConstants.CHARGE_YES.equals(coursePubVo.getCharge())) {
            //判断当前章节是否能试听
            ResponseResult<TeachplanVo> teachplanResult = contentClient.findTeachplanById(teachplanId);
            if (ErrorCode.SUCCESS.getCode() != teachplanResult.getCode()) {
                throw new BusinessException(ErrorCode.NOTFOUND);
            }
            TeachplanVo teachplanVo = teachplanResult.getData();
            //0是不支持试看
            if ("0".equals(teachplanVo.getIsPreview())) {
                //如果不支持试看，判断当前用户有没有购买此课程
                LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CourseRecord::getCoursePubId, coursePubId);
                wrapper.eq(CourseRecord::getUserId, AuthInfoThreadLocal.getUserId());
                CourseRecord courseRecord = courseRecordMapper.selectOne(wrapper);
                //如果没查到或者是没支付
                if (ObjectUtils.isEmpty(courseRecord) || OrdersConstants.NOT_PAID.equals(courseRecord.getPaid())) {
                    throw new BusinessException(ErrorCode.PARAMSERROR);
                }
            }
        }
        return mediaClient.gainMediaUrl(mediaId);
    }

    /**
     * 生成/更新课程发布的学习进度
     *
     * @param learningProgressDto 发布的id，课程大纲id,课程大纲名称
     * @return 结果
     */
    @Override
    public ResponseResult saveProgress(LearningProgressDto learningProgressDto) throws BusinessException {
        //判空
        if (ObjectUtils.isEmpty(learningProgressDto)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //查询学习记录
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseRecord::getCoursePubId, learningProgressDto.getCoursePubId());
        wrapper.eq(CourseRecord::getUserId, AuthInfoThreadLocal.getUserId());
        CourseRecord courseRecord = courseRecordMapper.selectOne(wrapper);
        //如果不为空，更新
        if (ObjectUtils.isNotEmpty(courseRecord)) {
            courseRecord.setTeachplanId(learningProgressDto.getTeachPlanId());
            courseRecord.setTeachplanName(learningProgressDto.getTeachPlanName());
            //更新数据库
            courseRecordMapper.updateById(courseRecord);
        } else {
            courseRecord = new CourseRecord();
            //根据课程发布id查询
            ResponseResult<CoursePubVo> result = contentClient.findById(learningProgressDto.getCoursePubId());
            if (ErrorCode.SUCCESS.getCode() != result.getCode()) {
                throw new BusinessException(ErrorCode.NOTFOUND);
            }
            CoursePubVo coursePubVo = result.getData();
            //封装数据
            courseRecord.setCourseId(coursePubVo.getCourseId());
            courseRecord.setCoursePubId(courseRecord.getCoursePubId());
            courseRecord.setCoursePubName(coursePubVo.getName());
            courseRecord.setCompanyId(coursePubVo.getCompanyId());
            courseRecord.setTeachplanId(learningProgressDto.getTeachPlanId());
            courseRecord.setTeachmode(coursePubVo.getTeachmode());
            courseRecord.setTeachplanName(learningProgressDto.getTeachPlanName());
            courseRecord.setUserId(AuthInfoThreadLocal.getUserId());
            courseRecord.setPaid(OrdersConstants.NOT_PAID);
            //保存
            courseRecordMapper.insert(courseRecord);
        }
        return ResponseResult.okResult();
    }
}
